package com.liao.controller;

import com.liao.bean.Codes;
import com.liao.bean.result.Code;
import com.liao.bean.result.Msg;
import com.liao.bean.result.PageResult;
import com.liao.bean.result.Result;
import com.liao.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private CodeService codeService;

    @ResponseBody
    @RequestMapping("/queryCodeListByPage")
    public PageResult<Codes> queryCodeListByPage(@RequestParam(defaultValue = "1") Integer currentPage,
                                                 @RequestParam(defaultValue = "5") Integer pageSize,
                                                 @RequestParam(defaultValue = "") String fieldName) throws Exception {
        PageResult<Codes> pageResult = codeService.queryCodeListByPage(currentPage,pageSize,fieldName);
        return pageResult;
    }

    @ResponseBody
    @RequestMapping("/addCode")
    public Result addCode(@RequestBody Codes code) throws Exception {

        codeService.addCode(code);
        return new Result(true, Code.CODE_ADD_SUCCESS, Msg.CODE_ADD_SUCCESS);

    }

    @ResponseBody
    @RequestMapping("/editCode")
    public Result editCode( @RequestBody Codes code) throws Exception {
        codeService.editCode(code);
        return new Result(true,Code.CODE_EDIT_SUCCESS, Msg.CODE_EDIT_SUCCESS);
    }

    @ResponseBody
    @RequestMapping("/deleteCode")
    public Result deleteCode(String codeId) throws Exception {
        codeService.deleteCode(codeId);
        return new Result(true,Code.CODE_DELETE_SUCCESS, Msg.CODE_DELETE_SUCCESS);
    }

    @ResponseBody
    @RequestMapping("/deleteCodeIds")
    public Result deleteCodeIds(@RequestParam("codeIds[]") List<String> codeIds) throws Exception {
        for (String codeId : codeIds) {
            try {
                codeService.deleteCode(codeId);
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,Code.CODE_DELETE_FAIL, Msg.CODE_DELETE_FAIL);
            }

        }
        return new Result(true,Code.CODE_DELETE_SUCCESS, Msg.CODE_DELETE_SUCCESS);
    }
}
